package cn.com.jdyun.controller;

import cn.com.jdyun.dto.UserCredit;
import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.pojo.User;
import cn.com.jdyun.service.UserService;
import cn.com.jdyun.util.CodeUtil;
import cn.com.jdyun.util.Constant;
import cn.com.jdyun.util.RedisUtil;
import cn.com.jdyun.util.WebConstants;
import cn.com.jdyun.util.reponse.Result;
import cn.com.jdyun.util.reponse.Status;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 判断邮箱或者手机号码是否存在
     *
     * @param userVertifyInfo
     * @return
     * @throws Exception
     */
    @PostMapping("/User/exists")
    public Result exists(String userVertifyInfo) throws Exception {

        if (StringUtils.isBlank(userVertifyInfo)) {
            return Result.create(Status.ILLEGAL_PARAMETER_VALUE, "输入账号不能为空", userVertifyInfo);
        }
        if (!WebConstants.validEmail(userVertifyInfo) && !WebConstants.validPhoneNumber(userVertifyInfo)) {
            return Result.create(Status.ILLEGAL_PARAMETER_VALUE, "输入账号（邮箱或手机号码）格式错误", userVertifyInfo);
        }
        if (userService.existUsername(userVertifyInfo)) {
            return Result.create(Status.ACCOUNT_EXISTS, "该账号已存在");
        }
        return Result.create(Status.ACCOUNT_NOT_EXISTS, "该账号不存在");
    }

    /**
     * 注册用户
     * @param userVertifyInfo //用户名
     * @param pwd             //用户密码
     * @param repeatPwd       //用户密码二次确认
     * @param refereeCode     //推荐码
     * @param code            //手机或邮箱验证码
     * @param nickName        //用户昵称
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/yx/transaction/reg")
    public Result regist(String userVertifyInfo, @RequestParam(required = false) String nickName, String pwd, String repeatPwd, @RequestParam(required = false) String refereeCode, String code, HttpSession session) throws Exception {
        //判断是否存在空值
        if(StringUtils.isEmpty(userVertifyInfo)){
            throw new BdexGatewayException("用户名不能为空!");
        }
        if(StringUtils.isEmpty(pwd)){
            throw new BdexGatewayException("密码不能为空!");
        }
        if(StringUtils.isEmpty(repeatPwd)){
            throw new BdexGatewayException("重复密码不能为空!");
        }
        if(StringUtils.isEmpty(code)){
            throw new BdexGatewayException("手机验证码不能为空!");
        }
        if (StringUtils.isBlank(nickName)) {
            nickName = userVertifyInfo;
        }
        //判断用户名是否存在
        if (userService.existUsername(userVertifyInfo)) {
            return Result.create(Status.ACCOUNT_EXISTS, userVertifyInfo);
        }
        User account = new User();
        if (StringUtils.isNotBlank(refereeCode)) {
            //判断推荐码是否正确
            String referee = userService.checkRefereeCode(refereeCode);
            if (StringUtils.isBlank(referee)) {
                return Result.create(Status.REFEREE_CODE_ERROR, refereeCode);
            }
            account.setReferee(referee);
        }
        WebConstants.validEmailOrTelphone(userVertifyInfo, code, session, account);
        account.setPhone(userVertifyInfo);
        //判断密码
        if (!pwd.equals(repeatPwd)) {
            return Result.create(Status.ACCOUNT_PWD_ERROR, "repeat error", repeatPwd);
        }
        account.setPhone(userVertifyInfo);
        account.setPassword(pwd);
        account.setNickName(nickName);
        //默认的等级为0
        account.setLevel(0);
        userService.regist(account);
        //密码设置为空不返回给前端
        account.setPassword(null);
        return Result.success(account);
    }

    /**
     * 发送手机或者邮箱验证码
     *
     * @param userVertifyInfo 用户名（手机或邮箱）
     * @param businessCode
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/User/vertify")
    public Result vertify(String userVertifyInfo, String businessCode, HttpSession session) throws Exception {

        Result r = new Result();
        String code = CodeUtil.getCard();
        if (WebConstants.validEmail(userVertifyInfo)) {
            //发送邮件给用户
            userService.sendVerificationCodeToEmail(userVertifyInfo, code + "");

            session.setAttribute(Constant.EMAIL, userVertifyInfo);
            session.setAttribute(Constant.EMAIL_CODE, code + "");
            session.setAttribute(Constant.CODE_SEND_TIME, System.currentTimeMillis());
            r.setMsg("验证码已发送到您的邮箱,请注意查收");
            return r;
        } else if (WebConstants.validPhoneNumber(userVertifyInfo)) {
//        	//限制每天智能发5条信息
//        	String nums = redisUtil.get(userVertifyInfo);
//        	if(nums == null) {
//        		redisUtil.set(userVertifyInfo, "1", 24*60*60);
//        	}else {
//        		int count = Integer.valueOf(nums);
//        		if(count <= 5) {
//        			count++;
//        			redisUtil.set(userVertifyInfo, count+"", 24*60*60);
//        		}else {
//        			return Result.create(Status.PHONE_CODE_SEND_LIMIT, "当日最多可发送5条短信", userVertifyInfo);
//        		}
//        	}
            String content = "";
            //发送短信给用户
            if (businessCode.equalsIgnoreCase(Constant.REGIST_CODE)) {
                content = "注册验证码是：" + code + "，10分钟内有效。";
            } else if (businessCode.equalsIgnoreCase(Constant.FINDPWD_CODE)) {
                content = "验证码：" + code + "，您的账号正在请求重置密码。10分钟内有效。";
            } else if (businessCode.equalsIgnoreCase(Constant.FINDTRADEPWD_CODE)) {
                content = "验证码：" + code + "，您的账号正在请求重置交易密码。10分钟内有效。";
            } else {
                throw new BdexGatewayException("获取验证码失败!");
            }
            userService.sendVerificationCodeToTelphone(URLEncoder.encode(content, "UTF-8"),
                    "JUSTSend", userVertifyInfo, "", "", "", "");
            //保存当前信息，用于验证
            session.setAttribute(Constant.PHONE_NUMBER, userVertifyInfo);
            session.setAttribute(Constant.PHONE_NUMBER_CODE, code + "");
            session.setAttribute(Constant.CODE_SEND_TIME, System.currentTimeMillis());
//            Long sessionSendTime = (Long)session.getAttribute(Constant.CODE_SEND_TIME);
//            System.out.println(sessionSendTime);
            r.setMsg("验证码已发送到您的手机,请注意查收");
            return r;
        } else {
            return Result.fail(userVertifyInfo);
        }
    }

    /**
     * 通过邮箱或手机号找回密码
     *
     * @param userVertifyInfo 用户名
     * @param code            手机或邮箱确认密码
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/User/findPwd")
    public Result findPwd(String userVertifyInfo, String code, String pwd, HttpSession session) throws BdexGatewayException, UnsupportedEncodingException {
        Result r = new Result();
        //判断是否存在空值
        if (StringUtils.isBlank(userVertifyInfo) || StringUtils.isBlank(code)) {
            Map<String, Object> params = new HashMap<>();
            params.put("username", userVertifyInfo);
            params.put("code", code);
            return Result.create(Status.ILLEGAL_PARAMETER_VALUE, "all fields are required", params);
        }
        if (!userService.existUsername(userVertifyInfo)) {
            return Result.create(Status.ACCOUNT_NAME_ERROR, userVertifyInfo);
        }
        User account = new User();
        //发送重置的密码至邮箱或手机
        WebConstants.validEmailOrTelphone(userVertifyInfo, code, session, account);
        String resetPwdCode = null;
        String content = null;
        //发送重置密码到邮箱或者手机
//        resetPwdCode =CodeUtil.getCard();
        content = "您当前的密码已重置密码为:" + resetPwdCode;
        if (StringUtils.isNotBlank(account.getEmail())) {
            userService.sendVerificationCodeToEmail(userVertifyInfo, content);
            account.setPassword(resetPwdCode);
            userService.updateUserPwdEmail(account);
        } else if (StringUtils.isNotBlank(account.getPhone())) {
            userService.sendVerificationCodeToTelphone(URLEncoder.encode(content, "UTF-8"),
                    "FindPwd", userVertifyInfo, "", "", "", "");
            account.setPassword(resetPwdCode);
            userService.updateUserPwdPhone(account);
        }

        r.setMsg("找回密码成功!");
        return r;
    }

    /**
     * 修改密码
     * @param userVertifyInfo 用户名
     * @param code            验证码
     * @param pwd             密码
     * @param repeatPwd       确认密码
     * @param session
     * @return
     * @throws BdexGatewayException
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/User/modifyPwd")
    public Result modifyPwd(String userVertifyInfo, String code, String pwd, String repeatPwd, HttpSession session) throws BdexGatewayException, UnsupportedEncodingException {
        Result r = new Result();
        if (!repeatPwd.equals(pwd)) {
            return Result.create(Status.ILLEGAL_PARAMETER_VALUE, "两次密码输入不一致", userVertifyInfo);
        }
        if (!userService.existUsername(userVertifyInfo)) {
            return Result.create(Status.ACCOUNT_NAME_ERROR, userVertifyInfo);
        }
        User account = new User();
        //判断用户账户
        WebConstants.validEmailOrTelphone(userVertifyInfo, code, session, account);
        account.setPassword(pwd);
        account.setPhone(userVertifyInfo);
        //修改密码
        if (StringUtils.isNoneBlank(account.getEmail())) {
            userService.updateUserPwdEmail(account);
        } else if (StringUtils.isNotBlank(account.getPhone())) {
            userService.updateUserPwdPhone(account);
        }
        r.setMsg("修改密码成功!");
        return r;
    }

    /**
     * 登陆
     *
     * @param username 用户名
     * @param password 密码
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/User/login")
    public Result login(String username, String password, HttpServletRequest request, HttpSession session) throws Exception {
        //判断是否存在空值
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            Map<String, Object> params = new HashMap<>();
            params.put("username", username);
            params.put("password", password);
            return Result.create(Status.ILLEGAL_PARAMETER_VALUE, "all fields are required", params);
        }
        if (!userService.existUsername(username)) {
            return Result.create(Status.ACCOUNT_NAME_ERROR, username);
        }
        UserCredit account = userService.login(username, password);
        if (account != null) {
            if (account.getFlag() == 0) {
                session.setAttribute(Constant.ACCOUNT_Mining, account);
                return Result.success(account);
            } else if (account.getFlag() == 1) {
                return Result.create(Status.ACCOUNT_LOCKED, account);
            } else if (account.getFlag() == 2) {
                return Result.create(Status.ACCOUNT_FOBIDDEN, account);
            }
        } else {
            return Result.create(Status.ACCOUNT_PWD_ERROR, password);
        }
        return Result.fail(username);
    }

    /**
     * 登出
     *
     * @return
     */
    @PostMapping("/User/logout")
    public Result logout(HttpSession session) {
        session.invalidate();
        session.setMaxInactiveInterval(0);
        return Result.success("");
    }
}
